package com.xuesinuo.ots.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.BeanUtils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.xuesinuo.ots.config.pojo.JavaBeanChanges;
import com.xuesinuo.xtool.Np;

/** JavaBean工具 */
public class BeanUtil {
    public static final TypeReference<Map<String, Object>> map_string_object = new TypeReference<Map<String, Object>>() {};

    /** 复制JavaBean */
    public static <E> E copy(Object from, E to) {
        BeanUtils.copyProperties(from, to);
        return to;
    }

    /** 获取对象变化（方便记录变更日志） */
    public static JavaBeanChanges getChanges(Object oldObject, Object newObject) {
        Map<String, Object> oldMap = JSON.parseObject(JSON.toJSONString(oldObject), map_string_object);
        Map<String, Object> newMap = JSON.parseObject(JSON.toJSONString(newObject), map_string_object);
        HashMap<String, Object> oldResult = new HashMap<>();
        HashMap<String, Object> newResult = new HashMap<>();
        oldMap.forEach((k, v) -> {
            if (newObject == null) {
                oldResult.put(k, v);
            } else if (newMap.containsKey(k)) {
                if (Np.i(v).notEq(newMap.get(k)) && newMap.get(k) != null) {
                    oldResult.put(k, v);
                }
            }
        });
        newMap.forEach((k, v) -> {
            if (oldObject == null) {
                newResult.put(k, v);
            } else if (oldMap.containsKey(k)) {
                if (Np.i(v).notEq(oldMap.get(k))) {
                    newResult.put(k, v);
                }
            } else {
                newResult.put(k, v);
            }
        });
        JavaBeanChanges changes = new JavaBeanChanges();
        changes.setOldMap(oldResult);
        changes.setNewMap(newResult);
        return changes;
    }
}
